import { Component } from '/src/components/component/component.js';
import { TemplateManager } from '/src/util/templatemanager/templatemanager.js'

export class DateComponent extends Component {
    constructor(container, options = {}) {
        super(container, options);
        this.type = options.type || 'day'; // 默认为 'day'
        this.templateUrl = '/src/components/component/searchbar/date-component.html'
    }

    async init() {
        // 在 init 中调用 render
        await this.render();
    }

    async render() {
        try {
            let html = await TemplateManager.loadTemplate(this.templateUrl, {
                cid: this.cid
            });

            this.container.html(html);

            // 为避免 ID 冲突，使用 cid（组件唯一ID）
            this.$typeSelect = this.container.find('#dateTypeSelected-' + this.cid);
            this.$beginDate = this.container.find('#beginDate-' + this.cid);
            this.$endDate = this.container.find('#endDate-' + this.cid);

            // 初始化
            this.initDate(this.type);
            this.bindEvents();
        } catch (error) {
            console.error('渲染 DateComponent 时出错:', error);
            this.container.append('<div class="text-danger">加载日期组件失败</div>');
        }
    }

    bindEvents() {
        // 监听下拉框变化
        this.$typeSelect.on('change', (e) => {
            const selectedValue = this.$typeSelect.val();
            this.type = selectedValue;
            this.initDate(selectedValue);
            // 触发自定义事件
            this.trigger('typeChange', selectedValue);
        });
    }

    initDate(type) {
        // 销毁之前的 datepicker（如果存在）
        if (this.$beginDate.data('datepicker')) {
            this.$beginDate.datepicker('destroy');
        }
        if (this.$endDate.data('datepicker')) {
            this.$endDate.datepicker('destroy');
        }

        const format = this.getFormatDate(type);

        let viewMode = 0;
        let minViewMode = 0;

        switch (type) {
            case 'year':
                viewMode = 2;
                minViewMode = 2;
                break;
            case 'month':
                viewMode = 1;
                minViewMode = 1;
                break;
            case 'day':
            default:
                viewMode = 0;
                minViewMode = 0;
                break;
        }

        this.$beginDate.datepicker({
            format,
            language: 'zh-CN',
            startView: viewMode,
            minViewMode: minViewMode,
            autoclose: true
        });

        this.$endDate.datepicker({
            format,
            language: 'zh-CN',
            startView: viewMode,
            minViewMode: minViewMode,
            autoclose: true
        });

        this.setDefaultDate(type);
    }

    setDefaultDate(type) {
        const endDate = new Date();
        let beginDate;

        switch (type) {
            case 'year':
                beginDate = new Date(endDate.getFullYear() - 12, 0, 1);
                break;
            case 'month':
                beginDate = new Date(endDate.getFullYear() - 1, endDate.getMonth(), 1);
                break;
            case 'day':
            default:
                beginDate = new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);
                break;
        }

        this.$beginDate.val(this.formatDate(beginDate, type));
        this.$endDate.val(this.formatDate(endDate, type));
    }

    formatDate(date, type) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');

        switch (type) {
            case 'year': return year.toString();
            case 'month': return `${year}-${month}`;
            case 'day': default: return `${year}-${month}-${day}`;
        }
    }

    getFormatDate(type) {
        switch (type) {
            case 'year': return 'yyyy';
            case 'month': return 'yyyy-mm';
            case 'day': default: return 'yyyy-mm-dd';
        }
    }

    /**
     * 获取当前选择的日期范围
     * @returns {{ type: string, beginDate: string, endDate: string }}
     */
    getDate() {
        return {
            type: this.type,
            beginDate: this.$beginDate.val(),
            endDate: this.$endDate.val()
        };
    }

    /**
     * 设置日期范围
     * @param {string} type
     * @param {string} beginDate
     * @param {string} endDate
     */
    setDate(type, beginDate, endDate) {
        this.$typeSelect.val(type).trigger('change'); // 会触发 initDate
        setTimeout(() => {
            this.$beginDate.val(beginDate);
            this.$endDate.val(endDate);
        }, 50); // 等待 datepicker 初始化
    }

    /**
     * 清空日期
     */
    clear() {
        this.$beginDate.val('');
        this.$endDate.val('');
    }

    destroy() {
        // 销毁 datepicker
        if (this.$beginDate?.data('datepicker')) {
            this.$beginDate.datepicker('destroy');
        }
        if (this.$endDate?.data('datepicker')) {
            this.$endDate.datepicker('destroy');
        }

        // 解绑事件
        // this.$typeSelect.off('.dateComponent');

        // 移除 DOM
        if (this.$el?.parent().length) {
            this.$el.remove();
        }

        this.off(); // 解绑自定义事件
        super.destroy?.();
    }
}